package com.example.factory.api.facade.impl;

import com.example.factory.api.dto.DtoRole;
import com.example.factory.api.dto.Response;
import com.example.factory.api.dto.assembler.RoleAssembler;
import com.example.factory.api.dto.form.DtoRoleForm;
import com.example.factory.api.facade.RoleFacade;
import com.example.factory.core.domain.RoleEntity;
import com.example.factory.core.repository.RoleEntityRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lei Tao
 */
@Service
public class RoleFacadeImpl implements RoleFacade {
    private final RoleAssembler roleAssembler;
    private final RoleEntityRepository repository;

    public RoleFacadeImpl(RoleAssembler roleAssembler, RoleEntityRepository repository) {
        this.roleAssembler = roleAssembler;
        this.repository = repository;
    }

    @Override
    public Response<List<DtoRole>> roleList() {
        List<RoleEntity> roleEntities = repository.selectAll();
        List<DtoRole> dtoRoles = roleAssembler.toDtoRole(roleEntities);
        return Response.success(dtoRoles);
    }

    @Override
    public Response<Void> deleteRole(String roleGuid) {
        RoleEntity roleEntity = repository.findByGuidAndArchivedFalse(roleGuid);
        roleEntity.archived();
        repository.save(roleEntity);
        return Response.success();
    }

    @Override
    public Response<DtoRole> retrieveRole(String roleGuid) {
        RoleEntity roleEntity = repository.findByGuidAndArchivedFalse(roleGuid);
        DtoRole dtoRole = roleAssembler.toDtoRole(roleEntity);
        return Response.success(dtoRole);
    }

    @Override
    public Response<DtoRole> saveOrUpdateRole(DtoRoleForm dtoRoleForm) {
        RoleEntity roleEntity = roleAssembler.toRole(dtoRoleForm);
        repository.save(roleEntity);
        DtoRole dtoRole = roleAssembler.toDtoRole(roleEntity);
        return Response.success(dtoRole);
    }
}
